package com.dict.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.dict.mapper.DictMapper;
import com.dict.pojo.ExcelDTO;
import jakarta.annotation.Resource;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 宋伟宁
 * @Date 2024/3/6
 * @Version 1.0
 **/
@Slf4j
@NoArgsConstructor //添加默认构造：反射用
public class ExeclListener implements ReadListener<ExcelDTO> {

    private static int count = 10;
    private List<ExcelDTO> list = new ArrayList<>(10);

    private DictMapper dictMapper;

    public ExeclListener(DictMapper dictMapper){
        this.dictMapper = dictMapper;
    }

    private void save(){
        log.info("保存数据");
        this.dictMapper.insertBatch(list);
        log.info("保存数据成功");
    }
    @Override
    public void invoke(ExcelDTO excelDTO, AnalysisContext analysisContext) {
         log.info("读取一条数据");
         list.add(excelDTO);
         if( this.list.size() >= count ){
             save();
             list.clear();
         }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
          save();
          log.info("读取完毕");
    }
}
